package com.zoe.app.dynamic;

import cn.hutool.core.map.MapUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.zoe.app.entity.DruidProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Set;

/**
 * @author zoe.Zhang
 * @date 2023/02/24
 * @description
 */
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
public class DataSourceProviderImpl implements DynamicDataSourceProvider {

    @Autowired
    private DruidProperties druidProperties;

    @Override
    public Map<String, DataSource> loadDataSourceMap() {
        int size = druidProperties.getDs().size();
        Map<String, DataSource> dataSourceMap = MapUtil.newHashMap(size);
        // 1:读取数据源配置
        Map<String, Map<String, String>> ds = druidProperties.getDs();
        Set<String> keySet = ds.keySet();
        for (String key : keySet) {
            Map<String, String> dataSourceBase = ds.get(key);
            try {
                DruidDataSource dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(dataSourceBase);

                // 2: 配置datasource的额外信息，循环添加到dataSourceMap中
                dataSourceMap.put(key, druidProperties.dataSource(dataSource));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return dataSourceMap;
    }
}
